package com.hao.tool.web.haotool;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import cn.hutool.poi.excel.sax.handler.RowHandler;
import com.hao.tool.common.util.HttpClientUtil;
import com.hao.tool.common.util.JsonKitUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.junit.Test;

import java.io.File;
import java.util.*;

/**
 * description
 *
 * @author RuiHaoZ on CMHK.jx
 * @date 2020-07-03 22:33
 */
public class TerminalAddHttpUtil {

    private static List<Map<String, Object>> terminalList = new ArrayList<>();

    private static final String ipAddr = "https://118.178.172.39:57330";


    @Test
    public void test() {
        String filePath = "/Users/haol/Downloads/手持机设备信息登记表-3.xlsx";
        ExcelUtil.read07BySax(filePath, 0, createParams());
//        createExcel(terminalList, "/Users/haol/Downloads/手持机设备信息登记表Result.xlsx");

    }


    @Test
    public void test2() {
        terminalIsExist("353022100111803");
    }

    public static void addBuild(Long rowIndex, String uniqueNo, String message, List<Object> rowList) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("rowIndex", rowIndex);
        params.put("uniqueNo", uniqueNo);
        params.put("message", message);
        params.put("opTime", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MS_PATTERN));
        List<Object> rowListBak = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            rowListBak.add(rowList.get(i));
        }
        params.put("rowList", JsonKitUtil.getString(rowListBak));
        if (message.equals("exist")) {
            return;
        }
        if (rowList.get(0) == null) {
            return;
        }
        String resultFilePath = "/Users/haol/develop/hao-tool-web/addFotc3.json";
        FileUtil.appendUtf8String(
                JsonKitUtil.getString(params) + "\n", new File(resultFilePath));
        terminalList.add(params);
    }

    public static void testAddHost(HashMap<String, String> params) {
        try {
            String sid = "48e4df57-a2b3-4da7-aad4-154e8e60d647";
            String remoteUrl = ipAddr + "/fotc-manage/api/v1/terminal";
            HashMap<String, String> heardMap = new HashMap<>();
            heardMap.put("Cookie", "sid=" + sid);
            heardMap.put("Content-Type", "application/json;charset=UTF-8");
            String response = HttpClientUtil.build().setHeaders(heardMap).sendPostFromRow(remoteUrl, JsonKitUtil.getString(params));
            System.out.println(params.get("uniqueCode") + ":" + response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static boolean terminalIsExist(String uniqueCode) {
        try {
            String remoteUrl = ipAddr + "/fotc-mobile/api/v1/terminals";
            HashMap<String, String> heardMap = new HashMap<>();
            heardMap.put("Content-Type", "application/x-www-form-urlencoded");
            heardMap.put("uniqueCode", uniqueCode);
            heardMap.put("branchAgency", "fx");
            heardMap.put("version", "3601.0.2000.3");

            String response = HttpClientUtil.build().setHeaders(heardMap).sendGet(remoteUrl, null);
            System.out.println(response);
            Map<String, String> resMap = JsonKitUtil.getObject(response, Map.class);
            if (!"00000".equalsIgnoreCase(resMap.get("status"))) {
                System.out.println(uniqueCode + ":" + response);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;

    }


    private static RowHandler createParams() {

        HashMap<String, String> params = new HashMap<>();

        params.put("agencyInfo", "fx_fangxing_方兴");
        params.put("enableIntercept", "1");
        params.put("enablePhoto", "0");
        params.put("enableCPC", "1");

        return (sheetIndex, rowIndex, rowlist) -> {
            if (rowlist.size() > 5 && rowIndex > 0 && rowIndex <10) {
                String uniqueCode = null;
                try {
                    uniqueCode = (String) rowlist.get(2);
                    if (StringUtils.isBlank(uniqueCode)) {
                        throw new Exception("not");
                    }
                    uniqueCode = uniqueCode.replace(" ", "");
                    if (uniqueCode.length() != 15) {
                        throw new Exception("length error");

                    }
                    String stationName = toStr(rowlist.get(0));

                    if (StringUtils.isBlank(stationName)) {
                        throw new Exception("the line is empty");
                    }
                    String terminalNo = toStr(rowlist.get(2));
                    String stationIdStr = toStr(rowlist.get(1));
                    if (StringUtils.isBlank(stationIdStr)) {
                        throw new Exception("stationId is null");
                    }

                    Long stationId = Long.parseLong(stationIdStr);
                    Long roadId = ((stationId / 100) * 100);
                    String enLaneNo = toStr(rowlist.get(3));
                    String exitLaneNo = toStr(rowlist.get(4));


                    params.put("uniqueCode", uniqueCode);
                    params.put("terminalNo", terminalNo);
                    params.put("roadId", String.valueOf(roadId));
                    params.put("stationId", String.valueOf(stationId));
                    params.put("enLaneNo", enLaneNo);
                    params.put("exitLaneNo", exitLaneNo);

                    params.put("roadUniqueId", String.valueOf(roadId));
                    boolean isExists = terminalIsExist(uniqueCode);
                    if (isExists) {
                        throw new Exception("exist");
                    }
                    addBuild(rowIndex, uniqueCode, "add", rowlist);
                    testAddHost(params);

                } catch (Exception e) {
                    addBuild(rowIndex, uniqueCode, e.getMessage(), rowlist);
                }
            }
        };
    }

    public static String toStr(Object o) {
        if (o == null) {
            return null;
        }
        if (o instanceof String) {
            return (String) o;
        } else if (o instanceof Long) {
            Long s = (Long) o;
            return String.valueOf(s);
        } else {
            return String.valueOf(o);
        }
    }


    public static void createExcel(List<Map<String, Object>> rows, String destFilePath) {
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(destFilePath);
        // 合并单元格后的标题行，使用默认标题样式
        writer.addHeaderAlias("uniqueNo", "设备码");
        writer.addHeaderAlias("opTime", "操作时间");
        writer.addHeaderAlias("rowList", "原表数据");
        writer.addHeaderAlias("rowIndex", "原表行数");
        StyleSet style = writer.getStyleSet();
        CellStyle cellStyle = style.getHeadCellStyle();
        writer.merge(rows.size() - 1, "添加结果");
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
        // 关闭writer，释放内存
        writer.close();
    }

    //{"uniqueCode":"1234","terminalNo":"1234","agencyInfo":"fx_fangxing_方兴","roadUniqueId":3600500,"enLaneNo":"51","exitLaneNo":"156","enableIntercept":"1","enablePhoto":"0","enableCPC":"1","stationId":"3600507","roadId":3600500}


}
